package org.alex.sample.web;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.alex.sample.VO.UserVO;
import org.alex.sample.model.Subject;
import org.alex.sample.model.User;
import org.alex.sample.page.PagerModel;
import org.alex.sample.service.IUserService;
import org.alex.sample.utils.ExcelUtils;
import org.alex.sample.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


@Controller
public class UserController {

	@Autowired
	private IUserService userService;
	
	@Autowired
	private LocaleResolver localeResolver;
	
	@Autowired
	private MessageSource messageSource;
	
	@RequestMapping(value="/changeLocale")
	public String changeLocale(HttpServletRequest request,HttpServletResponse response,String localeType) {
		if("en_US".equals(localeType)) {
			localeResolver.setLocale(request, response, Locale.US);
		}else if("zh_CN".equals(localeType)) {
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:/users";
	}
	
	@RequestMapping("/users")
	public String users(Model model) throws Exception{
		PagerModel<UserVO> list = userService.findAllByPage();
		model.addAttribute("userList",list);
		model.addAttribute("user", new User());
		model.addAttribute("edit",messageSource.getMessage("page.index.edit", null, LocaleContextHolder.getLocale()));
		return "user/userList";
	}
	
	//@Validated注解进行后台校验，BindingResult将校验结果保存在其中
	@RequestMapping(value="/userAdd",method=RequestMethod.POST)
	public String add(RedirectAttributes redirectAttributes,@Validated User user,BindingResult result){
		//判断校验如果有错误就返回添加页面
		if(result.hasErrors()){
			return "user/add";
		}
		try{
			userService.createUser(user);
			redirectAttributes.addFlashAttribute("message","添加一条学员记录成功");
		}catch(Exception e){
			redirectAttributes.addFlashAttribute("message","添加失败！");
			e.printStackTrace();
		}
		return "redirect:/users";
	}
	
	@RequestMapping(value="/userEdit/{id}",method=RequestMethod.GET)
	public String toEdit(Model model,@PathVariable Integer id) throws Exception {
		User user = userService.findUserById(id);
		model.addAttribute(user);
		return "user/edit";
	}
	
	//{id}传参占位符，在参数id加上@PathVariable绑定 
	@RequestMapping(value="/userEdit/{id}",method=RequestMethod.POST)
	public String edit(RedirectAttributes redirectAttribute,@Validated User user, BindingResult result) {
		if(result.hasErrors()) {
			return "user/edit";
		}
		try {
			userService.editUser(user);
			redirectAttribute.addFlashAttribute("message","修改成功");
		} catch (Exception e) {
			redirectAttribute.addFlashAttribute("message","修改失败");
			e.printStackTrace();
		}
		return "redirect:/users";
	}
	
	//{id}传参占位符，在参数id加上@PathVariable绑定 
	@RequestMapping(value="/userDelete/{id}")
	public String delete(RedirectAttributes redirectAttributes,@PathVariable Integer id) {
		try {
			userService.deleteUser(id);
			redirectAttributes.addFlashAttribute("message","成功删除一条学员记录");
		}catch(Exception e) {
			redirectAttributes.addFlashAttribute("message","删除一条学员记录失败");
			e.printStackTrace();
		}
		return "redirect:/users";
	}
	
	//批量删除
	@ResponseBody
	@RequestMapping(value = "/deleteMore")
	public Map<String, Object> deleteMoreUser(Model model, @RequestParam(name = "idArr") int[] idArr) throws Exception{
		Map<String, Object> messages = new HashMap<String, Object>();
		messages.put("success", false);
		userService.deleteMoreUser(idArr);
		messages.put("success", true);
		return messages;
	}
	
	@ResponseBody
	@RequestMapping(value = "/uploadFile")
	public Map<String, String> uploadFile(@RequestParam(value = "uploadFile") MultipartFile[] uploadFile){
		//获取文件
		MultipartFile uploadSimpleFile = uploadFile[0];
		//获取文件名
		String fileName = uploadSimpleFile.getOriginalFilename();
		//获取文件后缀名
		String postfix = fileName.substring(fileName.lastIndexOf(".") + 1);
		Map<String, String> message = new HashMap<String, String>();
		try {
			//判断文件类型只能是xlsx, xls
			if(ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix) || ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
				userService.saveStudentByExcel(uploadSimpleFile.getInputStream(), postfix);
				message.put("success", "批量导入成功");
			}else {
				message.put("error", "文件格式不正确");
			}
		}catch(Exception e) {
			e.printStackTrace();
			message.put("error", "批量导入失败");
		}
		return message;
	}
	
}
